package com.df.ez_game.server.gateway.tcp;

import com.baidu.bjf.remoting.protobuf.Codec;
import com.baidu.bjf.remoting.protobuf.ProtobufProxy;
import com.df.ez_game.server.msg.client.ClientReqMsg;
import com.df.ez_game.server.msg.client.ClientRespMsg;
import com.df.ez_game.server.gateway.GateWayServerNode;
import com.df.ez_game.server.gateway.UserManager;
import com.df.ez_game.tools.EzConstant;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j(topic = "gateway-codec")
@AllArgsConstructor
public class TcpGateWayCodec extends MessageToMessageCodec<ByteBuf, ClientRespMsg> {
    GateWayServerNode serverNode;

    @Override
    protected void encode(ChannelHandlerContext ctx, ClientRespMsg msg, List<Object> out) throws Exception {
        Codec<ClientRespMsg> codec = ProtobufProxy.create(ClientRespMsg.class);
        byte[] encode = null;
        try {
            encode = codec.encode(msg);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            encode = EzConstant.ProtoConstant.emptyBytes;
        }
        ByteBuf buffer = ctx.alloc().buffer(encode.length + 4);
        // 消息长度
        buffer.writeInt(encode.length);
        // 消息
        buffer.writeBytes(encode);
        int length = encode.length;
        UserManager.lifeCycle(cb->cb.respMsg(ctx,msg,length));
        out.add(buffer);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) {
        int length = msg.readInt();

        // 消息
        byte[] msgBytes = new byte[length-4];
        msg.readBytes(msgBytes);
        try {
            Codec<ClientReqMsg> codec = ProtobufProxy.create(ClientReqMsg.class);
            ClientReqMsg decode = codec.decode(msgBytes);
            UserManager.lifeCycle(handler->handler.receiveMsg(ctx,decode,true));
            out.add(decode);
        }catch (Exception e){
            UserManager.lifeCycle(handler->handler.receiveMsg(ctx,null,false));
            log.error(e.getMessage(),e);
        }
    }
}